package com.itheima.tlias08_14.controller;

import com.itheima.tlias08_14.annotation.Log;
import com.itheima.tlias08_14.entity.Emp;
import com.itheima.tlias08_14.paramobject.InsertEmp;
import com.itheima.tlias08_14.dto.SelectEmpById;
import com.itheima.tlias08_14.paramobject.SelectPageParam;
import com.itheima.tlias08_14.service.impl.EmpServiceImp;
import com.itheima.tlias08_14.utils.ResultUtil;
import com.itheima.tlias08_14.utils.ResultUtilEmp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
public class EmpController {

    @Autowired
    private EmpServiceImp empServiceImp;

    @GetMapping("/emps")
    public ResultUtil selectEmp(SelectPageParam selectPageParam) {

        if(selectPageParam.getPage() == 0 || selectPageParam.getPageSize() == 0){
            return ResultUtil.failure("页码或分页大小不能为零");
        }

        return empServiceImp.selectEmp(selectPageParam);
    }
    @GetMapping("/emps/list")
    public ResultUtil selectAllEmp(){
        List<Emp> emps = empServiceImp.selectAllEmp();
        int size = emps.size();
        return ResultUtil.success(emps);
    }


    @DeleteMapping("/emps")
    @Log
    public ResultUtilEmp deleteEmpById(@RequestParam("ids") List<Integer> id) {
        if(id.isEmpty()){
            return ResultUtilEmp.failure("你还没有选择数据，请选择要删除的数据");
        }
        int i = empServiceImp.deleteEmpById(id);
        return i>=1?ResultUtilEmp.success():ResultUtilEmp.failure();

    }

    @PostMapping("/emps")
    @Log
    public ResultUtilEmp insertEmp(@Validated @RequestBody InsertEmp emp) {
        int i = empServiceImp.insertEmp(emp);
        return i==1?ResultUtilEmp.success():ResultUtilEmp.failure("用户名已经存在");
    }

    @GetMapping("/emps/{id}")
    public ResultUtil selectById(@PathVariable("id") Integer id) {
        SelectEmpById selectEmpById = empServiceImp.selectEmpById(id);
        return selectEmpById!=null?ResultUtil.success(selectEmpById):ResultUtil.failure();
    }

    @PutMapping("/emps")
    @Log
    public ResultUtil updateEmp(@RequestBody SelectEmpById emp) {
        int i = empServiceImp.updateEmp(emp);
        return i==1?ResultUtil.success():ResultUtil.failure("用户名已存在");
    }






}
